<?php
namespace Admin\Controller;
use Common\Controller\BasicController;
/**
 * 菜单控制器
 */
class MenuController extends BasicController
{
  public function index(){
    $map = array();
    $map['keyword'] = I('get.kw');
    $cid = I('get.cid');
      if($cid === ''&&$cid!=-1){
      }else{
        $map['cid'] = $cid;
      }
    $page = $_REQUEST['p']?$_REQUEST['p']:1;
    $pageSize = $_REQUEST['pageSize']?$_REQUEST['pageSize']:10;
    $count = D('Menu')->getMenuCount($map);
    $menuList = D('Menu')->getMenuList($page,$pageSize,$map);
    foreach ($menuList as $k => $v) {
      $menuList[$k]['fMenu'] = D('Menu')->getFMenuByPid($v['pid']);
    }
    $res = new \Think\Page($count,$pageSize);
    $pageRes = $res->show();
    $this->assign('pageRes',$pageRes);
    $this->assign('list',$menuList);
    $this->display();
  }
  public function add(){
    if(IS_POST){
      $info = I('post.');
      if(!trim($info['title'])){
        ajaxReturn(400,"菜单名必须");
      }
      if(!trim($info['m'])){
        ajaxReturn(400,"模块名必须");
      }
      if(!trim($info['c'])){
        ajaxReturn(400,"控制器名必须");
      }
      if(!trim($info['f'])){
        ajaxReturn(400,"方法名必须");
      }
      if(!trim($info['status'])){
        ajaxReturn(400,"状态必须");
      }
      if(trim($info['menu_id'])){
        return $this->save($info);
      }
      $res = D('Menu')->addNewMenu($info);
      if($res){
        ajaxReturn(200,"新增菜单成功");
      }else{
        ajaxReturn(400,"新增菜单失败，请重试");
      }
    }
    $pid = D('Menu')->getPid();
    $this->assign('pid',$pid);
    $this->display();
  }
  public function setStatus(){
    if(IS_POST){
      $data = I('post.');
      $id = $data['id'];
      unset($data['id']);
      $status = $data['status'];
      try{
        $res = D('Menu')->updateMenu($id,$data);
        if($res === false){                 //tp save方法失败返回false，只有false的时候才是失败。
          return ajaxReturn(400,'修改失败');
        }else{
          return ajaxReturn(200,'修改成功');
        }
      }catch(Exception $e){
        return ajaxReturn(400,$e->getMessage());
      }
    }
  }
  public function edit(){
    $id = I('get.id');
    if(!$id){
      $this->error("id不存在");
    }
    $menu = D('Menu')->getMenuById($id);
    if(!$menu){
      $this->error("id不存在");
    }
    $pid = D('Menu')->getPid();
    $this->assign('pid',$pid);
    $this->assign('vo',$menu);
    $this->display();
  }
  public function save($data){
    $id = $data['menu_id'];
    unset($data['menu_id']);
    try{
      $res = D('Menu')->updateMenu($id,$data);
      if($res === false){                 //tp save方法失败返回false，只有false的时候才是失败。
        return ajaxReturn(400,'修改失败');
      }else{
        return ajaxReturn(200,'修改成功');
      }
    }catch(Exception $e){
        return ajaxReturn(400,$e->getMessage());
    }
  }
}
